package com.jerry.ball;

import lombok.Getter;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.RandomUtils;

import java.util.Arrays;
import java.util.List;

/**
 * @author wanggk
 * @Description
 * @date Created in 2021/9/9
 */
@Getter
@NoArgsConstructor
public class Game {

    private int roundTime;
    private Team team1;
    private Team team2;
    private List<Team> list;
    private Team attackTeam;

    public Game(int roundTime, Team team1, Team team2) {
        this.roundTime = roundTime;
        this.team1 = team1;
        this.team2 = team2;
        this.list = Arrays.asList(team1, team2);

    }

    public String start() {
        System.out.println("比赛即将开始，双方队伍的当家球星分别是" + team1.getPlayer() + "和" + team2.getPlayer());
        if (ThreadUtils.isMain()) {
            ThreadUtils.sleep(1000);
        }
        System.out.println("跳球。");
        this.attackTeam = RandomUtils.nextInt(1, 101) < 60 ? team1 : team2;
        System.out.println(attackTeam.getPlayer() + "获得球权。");
        for (int i = 0; i < roundTime; i++) {
            if (ThreadUtils.isMain()) {
                ThreadUtils.sleep(1000);
            }
            System.out.println("回合" + (i + 1));
            round(attackTeam);
        }
        return end();
    }

    private String end() {
        String result = team1.getPlayer() + "---总分：" + team1.getScore() + ", 进攻数：" + team1.getAttackTime() + ", 进球数：" + team1.getScoreTime()
                + ", 命中率：" + team1.getHitRate() + ", 篮板数：" + team1.getReboundTime();
        result = result + "\n";
        result = result + team2.getPlayer() + "---总分：" + team2.getScore() + ", 进攻数：" + team2.getAttackTime() + ", 进球数：" + team2.getScoreTime()
                + ", 命中率：" + team2.getHitRate() + ", 篮板数：" + team2.getReboundTime();
        System.out.println("\n---比赛结束！！！！！！！\n---我们来看一下赛后数据\n");
        System.out.println("回合数: " + roundTime);
        System.out.println(result);
        return result;
    }

    public void round(Team team) {
        if (team.attack()) {
            rebound();
        } else {
            attackTeam = list.stream().filter(v -> v != team).findFirst().get();
        }
    }

    private void rebound() {
        if (ThreadUtils.isMain()) {
            ThreadUtils.sleep(500);
        }
        System.out.println("争抢篮板！！！篮底下乱成了一锅粥,十个大肌霸挤在了一起。");
        if (ThreadUtils.isMain()) {
            ThreadUtils.sleep(500);
        }
        if (team1.getReboundTime() >= team2.getReboundTime()) {
            twoTimeAttach(team2);
        } else if (team1.getReboundTime() < team2.getReboundTime()) {
            twoTimeAttach(team1);
        } else {
            if (RandomUtils.nextInt(1, 101) < 51) {
                twoTimeAttach(team1);
            } else {
                twoTimeAttach(team2);
            }
        }
    }

    private void twoTimeAttach(Team team) {
        attackTeam = team;
        team.addRebound();
        round(attackTeam);
    }
}
